
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/pojo/vo/WordBookVo.dart';

import '../../pages/general/BookListView.dart';

class BookButton extends StatefulWidget {
  const BookButton({super.key,
    this.width = 160.0, this.height = 28.0, required this.onBookChanged
  });

  final double width;
  final double height;
  final VoidCallback onBookChanged;


  @override
  State<BookButton> createState() => _BookButtonState();
}

class _BookButtonState extends State<BookButton> {
  String _name = "请选择词书";


  void toBookListPage() {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const BookListView(),
      ),
    );
    widget.onBookChanged();
  }

  Future<void> _getSelectedBookName() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonString = prefs.getString("selectBook");
      if (jsonString == null) return;

      final jsonMap = jsonDecode(jsonString) as Map<String, dynamic>;
      final selectedBookInfo = WordBookVo.fromJson(jsonMap);

      if (mounted) {
        setState(() {
          _name = selectedBookInfo.name!;
        });
      }
    } catch (e) {
      debugPrint('加载书籍信息失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('无法加载已选书籍')),
      );
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => _getSelectedBookName());
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.width,
      height: widget.height,
      child: Hero(
        tag: "SelectedBook",
        child: ElevatedButton(
          onPressed: toBookListPage,
          style: ButtonStyle(
            padding: WidgetStateProperty.all(const EdgeInsets.fromLTRB(10, 0, 10, 0)),
            backgroundColor: WidgetStateProperty.all(Theme.of(context).colorScheme.primary),
            shape: WidgetStateProperty.all(
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _BookName(bookName: _name),
              const Icon(
                Icons.chevron_right,
                color: Colors.white,
              )
            ],
          ),
        ),
      ),
    );
  }
}

class _BookName extends StatelessWidget {
  const _BookName({super.key, required this.bookName});
  final String bookName;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Icon(
          Icons.book,
          size: 17,
          color: Colors.white,
        ),
        SizedBox.fromSize(size: const Size.fromWidth(5.0)),
        Text(
          bookName,
          style: const TextStyle(
            fontSize: 11,
            color: Colors.white,
          ),
        )
      ],
    );
  }
}


